<template>
	<view class="conditional-acceptance-details">
		<navBar :title="type === 7 ? '施工前条件验收审核' : '施工条件验收'" @goBack="uni.navigateBack()"></navBar>
		
		 <!-- #ifdef APP-PLUS || H5 -->
		 <scroll-view scroll-y :style="{height: `calc(100% - ${systemInfo.navbarHeight || 0}px - ${systemInfo.stateHeight || 0}px - ${systemInfo.bottomHeight || 0}px - ${type !== 3 && type !== 6 ? '46' : '0'}px)`}">
		 <!-- #endif -->
		 <!--  #ifdef MP-WEIXIN -->
		 <scroll-view scroll-y :style="{height: `calc(100% - ${systemInfo.bottomHeight || 0}px - ${type !== 3 && type !== 6 ? '46' : '0'}px)`}">
		 <!-- #endif -->
			<!-- <view class="title">总体监管项</view>
			<view class="list-content">
				<view v-for="(item, index) in totalityList" :key="index" class="item">
					<view class="num required">{{ item.num }}、</view>
					<view class="state-content">
						<view class="label" v-html="item.label"></view>
						<view class="state-list">
							<view @click="changeState(item, 'totalityList', index, 0)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '合规' || type !== 3 && type !== 6 && type !== 7" class="green" :class="[conditionalAcceptanceState[item.state] === '合规' ? 'active' : '']">合规</view>
							<view @click="changeState(item, 'totalityList', index, 1)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '不合规' || type !== 3 && type !== 6 && type !== 7" class="orange" :class="[conditionalAcceptanceState[item.state] === '不合规' ? 'active' : '']">不合规</view>
							<view @click="changeState(item, 'totalityList', index, 2)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '不涉及' || type !== 3 && type !== 6 && type !== 7" class="gray" :class="[conditionalAcceptanceState[item.state] === '不涉及' ? 'active' : '']">不涉及</view>
						</view>
					</view>
				</view>
			</view> -->
			
			<view class="title">具体监管项</view>
			<view class="list-content">
				<view v-for="(item, index) in concreteList" :key="index" class="item">
					<view class="num required">{{ item.num }}、</view>
					<view class="state-content">
						<!-- <view :ref="`label${index}`" class="label"></view> -->
						<view class="label" v-html="item.label"></view>
						<view class="details" v-html="item.details"></view>
						<view class="state-list">
							<view @click="changeState(item, 'concreteList', index, 0)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '合规' || type !== 3 && type !== 6 && type !== 7" class="green" :class="[conditionalAcceptanceState[item.state] === '合规' ? 'active' : '']">合规</view>
							<view @click="changeState(item, 'concreteList', index, 1)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '不合规' || type !== 3 && type !== 6 && type !== 7" class="orange" :class="[conditionalAcceptanceState[item.state] === '不合规' ? 'active' : '']">不合规</view>
							<view @click="changeState(item, 'concreteList', index, 2)" v-if="(type === 3 || type === 6 || type === 7) && conditionalAcceptanceState[item.state] === '不涉及' || type !== 3 && type !== 6 && type !== 7" class="gray" :class="[conditionalAcceptanceState[item.state] === '不涉及' ? 'active' : '']">不涉及</view>
						</view>
					</view>
				</view>
			</view>
			
			<view v-if="workOrderLogList.length" class="flow">
				<view class="flow-title">流程</view>
				<view v-for="(item, index) in workOrderLogList" :key="index" class="flow-content">
					<view class="state">
						<view class="state-content">
							<view class="state-title">{{ item.operationType }}</view>
							<view v-if="item.reviewState" class="state-label">
								<view>{{ item.reviewState }}</view>
							</view>
						</view>
						<view class="date">{{ item.operationDate }}</view>
					</view>
					<view class="name">{{ item.operationUserName }}</view>
					<view v-if="item.operationContent" class="idea">
						<view class="idea-title">审核意见：</view>
						<view class="idea-info">{{ item.operationContent }}</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view v-if="type !== 3 && type !== 6 && type !== 7" class="btn-content" :style="{paddingBottom: `${systemInfo.bottomHeight || 0}px`}">
			<u-button @click="tempSave" :loading="loading" type="warning" text="暂存"></u-button>
			<u-button @click="save" :loading="loading" type="primary" text="提交"></u-button>
		</view>
		<view v-if="type === 7" class="btn-content" :style="{paddingBottom: `${systemInfo.bottomHeight || 0}px`}">
			<u-button :loading="loading" @click="refuseExamine" type="warning" text="不同意施工"></u-button>
			<u-button :loading="loading" @click="consentExamine" type="primary" text="同意施工"></u-button>
		</view>
	</view>
</template>

<script>
	import { checkItemConfigurationList, conditionalAcceptanceSave, getConditionalAcceptance, conditionalAcceptanceAudit } from "@/api/conditionalAcceptance/constructionPlan.js"
	import { handleFormatDate } from "@/utils/date.js"
	import { getSystemHeightInfo, getPermission } from "@/utils/common.js"
	import permision from "@/js_sdk/wa-permission/permission.js"
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
import file from "../../../../mixins/file"
	export default {
		data() {
			return {
				totalityList: [],
				concreteList: [],
				// 状态类型 - 1: 未开始  2: 进行中  3: 待审核  4: 不同意施工  5: 同意待完善  6: 已完成  7: 审核
				type: 1,
				loading: false,
				id: null,
				conditionalAcceptanceState: {
					'acceptance_compliance_no_compliance': '不合规',
					'acceptance_compliance_compliance': '合规',
					'acceptance_compliance_not_involved': '不涉及',
				},
				workOrderLogList: [],
				systemInfo: {},
			}
		},
		async onLoad(options) {
			this.type = Number(options.type)
			this.id = Number(options.id)
			this.systemInfo = getSystemHeightInfo()
			await this.checkItemConfigurationList()
			this.getConditionalAcceptance()
			// #ifdef APP
			this.checkOpenGPSServiceByAndroid()
			// #endif
			// #ifdef MP-WEIXIN
			await this.getCurrentPosition()
			// #endif
			// let tempResult =  await this.getItemImage(70171)
			// console.log(tempResult, '哈哈哈')
		},
		methods: {
			changeState(data, key, index, value) {
				// 查看
				if ((this.type === 3 || this.type === 6 || this.type === 7) && data.pictureItemsNumber && !value) {
					const _type = this.type === 6 && data.pictureItemsNumber === 2 ? 3 : data.pictureItemsNumber === 2 ? 2 : data.pictureItemsNumber === 3 ? 4 :  data.pictureItemsNumber === 4 ? 5 : 1
					uni.navigateTo({ url: `/subpackage-enginner/pages/engineeringMaintenance/conditionalAcceptance/onditionalAcceptanceImage?state=2&titleText=${data.titleText}&type=${_type}${data.docId ? ('&docId=' + data.docId) : ''}${data.docId1 && data.pictureItemsNumber === 2 ? ('&docId1=' + data.docId1) : ''}${(data.docId1 || data.docId2) && data.pictureItemsNumber === 3 ? ('&docId2=' + (data.docId1 || data.docId2)) : ''}${data.pictureItemsNumber === 4 ? ('&docId2=' + (data.docId1 || data.docId2)) + ('&docId4=' + data.docId4) : ''}` })
					return
				}
				const keys = ['acceptance_compliance_compliance', 'acceptance_compliance_no_compliance', 'acceptance_compliance_not_involved']
				if (value === 0) {
					const type = key === 'totalityList' ? 1 : 2
					if (!data.pictureItemsNumber) {
						this.$set(this[key], index, { ...this[key][index], state: keys[value] })
						return
					} else {
						const state = this.type === 3 || this.type === 6 ? 2 : 1
						const _type = this.type === 6 && data.pictureItemsNumber === 2 ? 3 : data.pictureItemsNumber === 2 ? 2 : data.pictureItemsNumber === 3 ? 4 :  data.pictureItemsNumber === 4 ? 5 : 1
						uni.navigateTo({ url: `/subpackage-enginner/pages/engineeringMaintenance/conditionalAcceptance/onditionalAcceptanceImage?state=${state}&titleText=${data.titleText}&type=${_type}${data.docId ? ('&docId=' + data.docId) : ''}${data.docId1 && data.pictureItemsNumber === 2 ? ('&docId1=' + data.docId1) : ''}${(data.docId1 || data.docId2) && data.pictureItemsNumber === 3 ? ('&docId2=' + (data.docId1 || data.docId2)) : ''}${data.pictureItemsNumber === 4 ? ('&docId2=' + (data.docId1 || data.docId2)) + ('&docId4=' + data.docId4) : ''}` })
						this.$$off("_changeState")
						this.$$on("_changeState", ({ docId, docId1, docId2, docId4 }) => {
							this.$set(this[key], index, { ...this[key][index], state: keys[value], docId, docId1, docId2, docId4 })
							console.log(data, key, index, value, 'sssssss');
						})
					}
				} else {
					this.$set(this[key], index, { ...this[key][index], state: keys[value], docId: undefined, docId1: undefined })
				}
			},
			checkItemConfigurationList() {
				return new Promise(resolve => {
					checkItemConfigurationList({
						currPage: 1,
						pageSize: 20,
						params: {}
					}).then(res => {
						if (res && res.result && res.result.list) {
							this.concreteList = res.result.list.filter(item => item.state).map((item, index) => {
								const titleStyle = item.titleStyle ? JSON.parse(item.titleStyle) : null
								const contentStyle = item.contentStyle ? JSON.parse(item.contentStyle) : null
								let label = !titleStyle ? `<p>${item.titleText || ''}</p>` : `<p class="aaa">${item.titleText.substring(0, titleStyle.indexStart || 0)}<span class="bbb">${item.titleText.substring(titleStyle.indexStart, titleStyle.indexEnd)}</span>${item.titleText.substring(titleStyle.indexEnd || 0, item.titleText.length)}</p>`
								let details = !contentStyle ? `<p>${item.contentText || ''}</p>` : `<p class="aaa">${item.contentText.substring(0, contentStyle.indexStart || 0)}<span class="bbb">${item.contentText.substring(contentStyle.indexStart, contentStyle.indexEnd)}</span>${item.contentText.substring(contentStyle.indexEnd || 0, item.contentText.length)}</p>`
								// #ifdef APP-PLUS || H5
								label = label.replace(/<p/g, "<uni-view").replace(/p>/g, "uni-view>").replace(/<span/g, "<uni-text").replace(/span>/g, "uni-text>").replace(/class=\"red\"/g, `style=\"color: #F56C6C;\"`)
								details = details.replace(/<p/g, "<uni-view").replace(/p>/g, "uni-view>").replace(/<span/g, "<uni-text").replace(/span>/g, "uni-text>").replace(/class=\"red\"/g, `style=\"color: #F56C6C;\"`)
								// #endif
								return {
									...item,
									label,
									details,
									num: (index + 1).toString().padStart(2, '0'),
									state: 'acceptance_compliance_no_compliance',
								}
							})
						}
					}).finally(() => {
						resolve()
					})
				})
			},
			getConditionalAcceptance() {
				getConditionalAcceptance({ id: this.id }).then(res => {
					if (res && res.result) {
						if (res.result.conditionalAcceptanceList) {
							for (const item of res.result.conditionalAcceptanceList) {
								let index = this.totalityList.findIndex(item1 => item1.id === item.checkItemConfigurationId)
								if (index !== -1) {
									this.$set(this.totalityList, index, { ...this.totalityList[index], state: item.status, _id: item.id, docId: item.docId, docId1: item.doc1Id, docId2: item.pictureItemsNumber !== 4 ? item.doc2Id : undefined, docId4: item.pictureItemsNumber === 4 ? item.doc2Id : undefined })
								}
								else {
									index = this.concreteList.findIndex(item1 => item1.id === item.checkItemConfigurationId)
									if (index !== -1) {
										this.$set(this.concreteList, index, { ...this.concreteList[index], state: item.status, _id: item.id, docId: item.docId, docId1: item.doc1Id, docId2: item.pictureItemsNumber !== 4 ? item.doc2Id : undefined, docId4: item.pictureItemsNumber === 4 ? item.doc2Id : undefined })
									}
								}
							}
						}
						if (res.result.workOrderLogList) {
							this.workOrderLogList = res.result.workOrderLogList.map(item => ({
								...item,
								operationDate: item.operationDate ? handleFormatDate(new Date(item.operationDate), 3) : ''
							}))
						}
					}
				})
			},
			async getItemImage(docId, conditionalAcceptanceId) {
				return await new Promise((resolve, reject) => {
					getPicture({docId}).then(res => {
						resolve(res.result.map(it => ({
							typeName:'',
							conditionalAcceptanceId:conditionalAcceptanceId,
							...it,
						})));
					}).catch(err => reject(err))
				})
			},
			async tempSave() {
				if (this.loading) {
					return
				}
				this.loading = true
				try {
					await this.conditionalAcceptanceSave({ isSave: true })
					uni.showToast({ title: "暂存成功", icon: "none" })
					const tiemout = setTimeout(() => {
						clearTimeout(tiemout)
						uni.navigateBack()
						this.loading = false
					}, 500)
				} catch(e) {
					uni.showToast({ title: e ? e : "暂存失败，请重新尝试", icon: "none" })
					this.loading = false
				}
			},
			async save() {
				if (this.loading) {
					return
				}
				this.loading = true
				for (const item of this.totalityList) {
					if (this.conditionalAcceptanceState[item.state] === '不合规') {
						uni.showToast({ title: "含不合规项，无法提交", icon: "none" })
						this.loading = false
						return
					}
				}
				for (const item of this.concreteList) {
					if (this.conditionalAcceptanceState[item.state] === '不合规') {
						uni.showToast({ title: "含不合规项，无法提交", icon: "none" })
						this.loading = false
						return
					}
				}
				try {
					await this.conditionalAcceptanceSave({ isSave: false })
					uni.showToast({ title: "提交成功", icon: "none" })
					const tiemout = setTimeout(() => {
						clearTimeout(tiemout)
						uni.navigateBack()
						this.loading = false
					}, 500)
				} catch(e) {
					uni.showToast({ title: e ? e : "提交失败，请重新尝试", icon: "none" })
					this.loading = false
				}
			},
			conditionalAcceptanceSave(params) {
				return new Promise(async (resolve, reject) => {
					const conditionalAcceptances = []
					for (const item of this.totalityList) {
						conditionalAcceptances.push({
							constructionPlanId: this.id,
							docId: item.docId ? item.docId : undefined,
							doc1Id: (item.docId2 ? item.docId2 : item.docId1) || undefined,
							checkItemConfigurationId: item.id,
							name: item.name,
							content: item.content ? item.content : undefined,
							code: item.code,
							status: item.state,
							id: item._id
						})
					}
					for (const item of this.concreteList) {
						conditionalAcceptances.push({
							constructionPlanId: this.id,
							docId: item.docId ? item.docId : undefined,
							doc1Id: (item.docId2 ? item.docId2 : item.docId1) || undefined,
							doc2Id: item.docId4 ? item.docId4 : undefined,
							checkItemConfigurationId: item.id,
							name: item.name,
							content: item.content ? item.content : undefined,
							code: item.code,
							status: item.state,
							id: item._id,
						})
					}
					// #ifdef APP-PLUS
					const result = await this.getCurrentPosition()
					if (!result) {
						reject("位置信息获取失败!请检查是否打开Gps服务或是否允许获取当前位置")
						return
					}
					let str = await getPermission('android.permission.ACCESS_FINE_LOCATION')
					if(str !== '已获得授权') {
						uni.showModal({
							title: '提示',
							content: '请先允许获取位置定位权限',
							success: res => {
								if (res.confirm) {
									permision.gotoAppPermissionSetting()
								} else {
									reject("位置信息获取失败!请检查是否打开Gps服务或是否允许获取当前位置")
									return
								}
							}
						});
					}
					// #endif
					// #ifndef H5
					if(!this.location || this.location === '0.0065,0.006') {
						reject("位置信息获取失败!请检查是否打开Gps服务或是否允许获取当前位置")
						return
					}
					// #endif
					let resq  = {
						ConstructionPlanId: this.id,
						conditionalAcceptances,
						location: this.location || undefined,
						...params
					}
					console.log(resq)
					// return
					conditionalAcceptanceSave(resq).finally(() => {
						resolve()
					})
				})
			},
			/**检查是否打开GPS功能（android）**/
			checkOpenGPSServiceByAndroid() {			
			  let system = uni.getSystemInfoSync();// 获取系统信息
			  if (system.platform === 'android') { // 判断平台
			    var context = plus.android.importClass("android.content.Context");
			    var locationManager = plus.android.importClass("android.location.LocationManager");
			    var main = plus.android.runtimeMainActivity();
			    var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			      uni.showModal({
			        title: '提示',
			        content: '请打开定位服务功能',
			        showCancel: false, // 不显示取消按钮
			        success() {
			          if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			            var Intent = plus.android.importClass('android.content.Intent');
			            var Settings = plus.android.importClass('android.provider.Settings');
			            var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
			            main.startActivity(intent); // 打开系统设置GPS服务页面
			          }
			        }
			      });
			    }
			  } 
			},
			async getCurrentPosition() {
				return await new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success:async (res) => {
							if(!res.latitude || !res.longitude) {
								uni.showToast({ title:'无法获取您的位置信息,请检查是否已打开定位服务', icon:'none', mask:true })
								resolve(false)
							}
							else {
								this.location = this.gcj02tobd09(res.latitude, res.longitude)
								resolve(true)
							}
						},
						fail: (err) => {
							uni.showToast({ title:'无法获取您的位置信息,请检查是否已打开定位服务', icon:'none', mask:true })
							resolve(false)
						},
					});
				})
			},
			gcj02tobd09(lng, lat) {
			   var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
			   var lat = +lat;
			   var lng = +lng;
			   var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
			   var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
			   var bd_lng = z * Math.cos(theta) + 0.0065;
			   var bd_lat = z * Math.sin(theta) + 0.006;
			   return bd_lng + ',' + bd_lat
			 },
			refuseExamine() {
				uni.navigateTo({ url: `/subpackage-enginner/pages/engineeringMaintenance/conditionalAcceptance/auditOpinion` })
				this.$$off("monitorOpinion")
				this.$$on("monitorOpinion", data => {
					this.loading = true
					conditionalAcceptanceAudit({
						constructionPlanId: this.id,
						isConsentConstruction: false,
						auditOpinion: data,
						projectId: null
					}).then(() => {
						uni.navigateBack({ delta: 2 })
						this.loading = false
					})
				})
			},
			consentExamine() {
				if (this.loading) {
					return
				}
				this.loading = true
				conditionalAcceptanceAudit({
					constructionPlanId: this.id,
					isConsentConstruction: true,
					projectId: null
				}).then(() => {
					uni.showToast({ title: "操作成功", icon: "none" })
					const timeout = setTimeout(() => {
						clearTimeout(timeout)
						uni.navigateBack()
						this.loading = false
					}, 500)
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.conditional-acceptance-details {
		font-size: 16px;
		box-sizing: border-box;
		height: 100vh;
		/* #ifdef MP-WEIXIN */
		padding-top: 200rpx;
		/* #endif */
		.title {
			padding: 17px 17px 9px;
			line-height: 25px;
			color: #22204e;
			font-size: 18px;
			font-weight: bold;
			background: #f5f7fa;
		}
		.required {
			&::before {
				content: "*";
				color: #ff4646;
				font-size: 16px;
			}
		}
		.list-content {
			.item {
				display: flex;
				padding: 17px 15px 13px;
				.num {
					width: 41px;
					flex-shrink: 0;
					color: #22204e;
					font-weight: bold;
						line-height: 29px;
				}
				.state-content {
					flex: 1;
					.label {
						line-height: 29px;
						color: #22204e;
						font-weight: bold;
					}
					.state-list {
						display: flex;
						align-items: center;
						margin-top: 15px;
						> view {
							background: #f5f7fa;
							font-size: 16px;
							font-weight: bold;
							border-radius: 50px;
							padding: 4px 14px;
							margin-right: 12px;
							color: #768293;
						}
						.green {
							&.active {
								background: #45c552;
								color: #fff;
							}
						}
						.orange {
							&.active {
								background: #ff8a2c;
								color: #fff;
							}
						}
						.gray {
							&.active {
								background: #e4e4e4;
								color: #717171;
							}
						}
					}
					.details {
						line-height: 22px;
						margin-top: 9px;
						color: #778599;
						font-size: 14px;
						font-weight: bold;
					}
					::v-deep .label {
						> view, rich-text {
							line-height: 29px;
							color: #22204e;
							font-weight: bold;
							> text, span {
								color: #F56C6C;
							}
						}
						> rich-text {
							.aaa {
								line-height: 29px;
								color: #22204e;
								font-weight: bold;
								.bbb {
									color: #F56C6C;
								}
							}
						}
					}
					::v-deep .details {
						> view {
							line-height: 22px;
							margin-top: 9px;
							color: #778599;
							font-size: 14px;
							font-weight: bold;
							> text {
								color: #F56C6C;
							}
						}
						> rich-text {
							.aaa {
								line-height: 29px;
								color: #22204e;
								font-weight: bold;
								.bbb {
									color: #F56C6C;
								}
							}
						}
					}
				}
			}
		}
		.btn-content {
			height: 46px;
			line-height: 46px;
			display: flex;
			align-items: center;
			justify-content: center;
			position: fixed;
			bottom: 0;
			width: 100vw;
			> * {
				flex: 1;
				border-radius: 0;
			}
		}
		.flow {
			border-top: 15px solid #f5f7fa;
			.flow-title {
				color: #22204e;
				line-height: 25px;
				padding: 18px 15px 30px;
				font-size: 18px;
				font-weight: bold;
			}
			.flow-content {
				border-left: 1px dashed #86b5fb;
				padding-left: 20px;
				margin: 0 26px 0 42px;
				position: relative;
				&::before {
					content: "";
					position: absolute;
					top: -8px;
					left: -8px;
					width: 16px;
					height: 16px;
					background: radial-gradient(#2f80ed 45%, rgba(47, 128, 237, 0.3) 45%);
					border-radius: 50%;
				}
				&:last-child {
					&::after {
						content: "";
						position: absolute;
						bottom: -8px;
						left: -8px;
						width: 10px;
						height: 20px;
						background: #fff;
					}
				}
				.state {
					display: flex;
					align-items: center;
					justify-content: space-between;
					height: 33px;
					transform: translateY(-16px);
					.state-content {
						display: flex;
						align-items: center;
						.state-title {
							color: #2f80ed;
							font-size: 18px;
							font-weight: bold;
							margin-right: 10px;
						}
						.state-label {
							background: linear-gradient( 90deg, #FF2B2B 0%, #FF603D 100%);
							border-radius: 2px 2px 2px 2px;
							color: #fff;
							font-weight: bold;
							font-size: 14px;
							transform: skewX(-20deg);
							padding: 0 6px;
							border-radius: 4px;
							view {
								 transform: skewX(20deg);
							}
						}
					}
					.date {
						color: #6a819e;
						font-weight: 500;
						font-size: 13px;
					}
				}
				.name {
					color: #4b5664;
					font-size: 16px;
					font-weight: bold;
					line-height: 22px;
					padding-bottom: 16px;
					transform: translateY(-10px);
				}
				.idea {
					font-size: 16px;
					font-weight: bold;
					padding-bottom: 16px;
					transform: translateY(-10px);
					.idea-title {
						color: #22204e;
						margin-bottom: 4px;
						line-height: 22px;
					}
					.idea-info {
						color: #778599;
						line-height: 26px;
					}
				}
			}
		}
	}
</style>
